package com.new1cloud.file.upload.client.bootstrap;

import com.new1cloud.file.domain.FileUploadBasicInfo;
import com.new1cloud.file.tools.ThatStringUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Objects;

/**
 * 子客户端
 */
@Setter
public class FileUploadSubClient {
    protected final Logger log = LoggerFactory.getLogger(this.getClass());

    /**
     * 服务端地址
     */
    private String serverAddress;
    /**
     * 服务端口
     */
    private int port;

    /**
     * 待发送文件的基本信息(本次发送涉及到的文件的基本信息)
     */
    private List<FileUploadBasicInfo> sendFileBasicInfos;

    /**
     * 客户端启动器
     */
    private Bootstrap clientBootstrap;

    /**
     * 客户端名称
     */
    private String clientName;

    public FileUploadSubClient(String serverAddress, int port,
                               List<FileUploadBasicInfo> sendFileBasicInfos, Bootstrap clientBootstrap) {
        this.serverAddress = serverAddress;
        this.port = port;
        this.sendFileBasicInfos = sendFileBasicInfos;
        this.clientBootstrap = clientBootstrap;
        this.clientName = "客户端_" + ThatStringUtil.getRandom(4);
    }

    public FileUploadSubClient(String serverAddress, int port,
                               List<FileUploadBasicInfo> sendFileBasicInfos, Bootstrap clientBootstrap, String clientName) {
        this.serverAddress = serverAddress;
        this.port = port;
        this.sendFileBasicInfos = sendFileBasicInfos;
        this.clientBootstrap = clientBootstrap;
        this.clientName = clientName;
    }

    public Channel execute() {
        if(Objects.isNull(sendFileBasicInfos) || sendFileBasicInfos.isEmpty()) {
            log.error("sendFileBasicInfos不能为空.");
            return null;
        }

        try {
            ChannelFuture f = clientBootstrap.connect(serverAddress, port).sync();
            //直接发送待上传文件的基本信息到服务端
            Channel channel = f.channel();
            this.sendFileBasicInfos.forEach(fileBaseInfo -> {
                channel.writeAndFlush(fileBaseInfo).addListener(future -> {
                    log.info("[{}]文件({})的FileUploadBasicInfo已向服务端发送成功.", this.clientName, fileBaseInfo.getFileName());
                });
            });
            channel.closeFuture().sync();
            return channel;
        } catch (InterruptedException e) {
            log.error("客户端({})连接异常, ", this.clientName, e);
        }
        return null;
    }
}